#include "stdafx.h"
#include "net/POP3ClientSession.hpp"
#include "net/MailStream.hpp"
#include "utils/numberformatter.hpp"
using JHCPP::utils::CNumberFormatter;
#include "stream/StreamCopier.hpp"
using JHCPP::stream::CStreamCopier;

NET_NAMESPACE_BEGIN

class CDialogStreamBuf: public UnbufferedStreamBuf
{
public:
	CDialogStreamBuf(CDialogSocket& socket) : m_socket(socket)
	{
	}

	~CDialogStreamBuf()
	{
	}

private:
	int readFromDevice()
	{
		return m_socket.get();
	}

	CDialogSocket& m_socket;
};


class CDialogIOS : public virtual std::ios
{
public:
	CDialogIOS(CDialogSocket& socket) : m_buf(socket)
	{
	}

	~CDialogIOS()
	{
	}

	CDialogStreamBuf* rdbuf()
	{
		return &m_buf;
	}

protected:
	CDialogStreamBuf m_buf;
};


class CDialogInputStream : public CDialogIOS, public std::istream
{
public:
	CDialogInputStream(CDialogSocket& socket) : CDialogIOS(socket), std::istream(&m_buf)
	{
	}

	~CDialogInputStream()
	{
	}
};


CPOP3ClientSession::CPOP3ClientSession(const CStreamSocket& socket) : m_socket(socket), m_isOpen(true)
{
}

CPOP3ClientSession::CPOP3ClientSession(const std::string& host, UInt16 port)
	: m_socket(CSocketAddress(host, port)), m_isOpen(true)
{
}

CPOP3ClientSession::~CPOP3ClientSession()
{
	try
	{
		close();
	}
	catch (...)
	{
	}
}

void CPOP3ClientSession::setTimeout(const CTimeSpan& timeout)
{
	m_socket.setReceiveTimeout(timeout);
}

CTimeSpan CPOP3ClientSession::getTimeout() const
{
	return m_socket.getReceiveTimeout();
}

void CPOP3ClientSession::login(const std::string& username, const std::string& password)
{
	std::string response;
	m_socket.receiveMessage(response);
	if (!isPositive(response)) throw POP3Exception("The POP3 service is unavailable", response);
	sendCommand("USER", username, response);
	if (!isPositive(response)) throw POP3Exception("Login rejected for user", response);
	sendCommand("PASS", password, response);
	if (!isPositive(response)) throw POP3Exception("Password rejected for user", response);
}

void CPOP3ClientSession::close()
{
	if (m_isOpen)
	{
		std::string response;
		sendCommand("QUIT", response);
		m_socket.close();
		m_isOpen = false;
	}
}

int CPOP3ClientSession::messageCount()
{
	std::string response;
	sendCommand("STAT", response);
	if (!isPositive(response)) throw POP3Exception("Cannot determine message count", response);
	std::string::const_iterator it  = response.begin();
	std::string::const_iterator end = response.end();
	int count = 0;
	while (it != end && !CAscii::isSpace(*it)) ++it;
	while (it != end && CAscii::isSpace(*it)) ++it;
	while (it != end && CAscii::isDigit(*it)) count = count*10 + *it++ - '0';
	return count;
}

void CPOP3ClientSession::listMessages(MessageInfoVec& messages)
{
	messages.clear();
	std::string response;
	sendCommand("LIST", response);
	if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
	m_socket.receiveMessage(response);
	while (response != ".")
	{
		MessageInfo info = {0, 0};
		std::string::const_iterator it  = response.begin();
		std::string::const_iterator end = response.end();
		while (it != end && CAscii::isDigit(*it)) info.id = info.id*10 + *it++ - '0';
		while (it != end && CAscii::isSpace(*it)) ++it;
		while (it != end && CAscii::isDigit(*it)) info.size = info.size*10 + *it++ - '0';
		messages.push_back(info);
		m_socket.receiveMessage(response);
	}
}

void CPOP3ClientSession::retrieveMessage(int id, CMailMessage& message)
{
	std::string response;
	sendCommand("RETR", CNumberFormatter::format(id), response);
	if (!isPositive(response)) throw POP3Exception("Cannot retrieve message", response);
	CDialogInputStream sis(m_socket);
	CMailInputStream mis(sis);
	message.read(mis);
	while (mis.good()) mis.get(); // read any remaining junk
}

void CPOP3ClientSession::retrieveMessage(int id, CMailMessage& message, CPartHandler& handler)
{
	std::string response;
	sendCommand("RETR", CNumberFormatter::format(id), response);
	if (!isPositive(response)) throw POP3Exception("Cannot retrieve message", response);
	CDialogInputStream sis(m_socket);
	CMailInputStream mis(sis);
	message.read(mis, handler);
	while (mis.good()) mis.get(); // read any remaining junk
}

void CPOP3ClientSession::retrieveMessage(int id, std::ostream& ostr)
{
	std::string response;
	sendCommand("RETR", CNumberFormatter::format(id), response);
	if (!isPositive(response)) throw POP3Exception("Cannot retrieve message", response);
	CDialogInputStream sis(m_socket);
	CMailInputStream mis(sis);
	CStreamCopier::copyStream(mis, ostr);
}

void CPOP3ClientSession::retrieveHeader(int id, CMessageHeader& header)
{
	std::string response;
	sendCommand("TOP", CNumberFormatter::format(id), "0", response);
	if (!isPositive(response)) throw POP3Exception("Cannot retrieve header", response);
	CDialogInputStream sis(m_socket);
	CMailInputStream mis(sis);
	header.read(mis);
	// skip stuff following header
	mis.get(); // \r
	mis.get(); // \n
}

void CPOP3ClientSession::deleteMessage(int id)
{
	std::string response;
	sendCommand("DELE", CNumberFormatter::format(id), response);
	if (!isPositive(response)) throw POP3Exception("Cannot mark message for deletion", response);
}

bool CPOP3ClientSession::sendCommand(const std::string& command, std::string& response)
{
	m_socket.sendMessage(command);
	m_socket.receiveMessage(response);
	return isPositive(response);
}

bool CPOP3ClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
	m_socket.sendMessage(command, arg);
	m_socket.receiveMessage(response);
	return isPositive(response);
}

bool CPOP3ClientSession::sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response)
{
	m_socket.sendMessage(command, arg1, arg2);
	m_socket.receiveMessage(response);
	return isPositive(response);
}

bool CPOP3ClientSession::isPositive(const std::string& response)
{
	return response.length() > 0 && response[0] == '+';
}


NET_NAMESPACE_END
